# -*- coding: utf-8 -*-

from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError


class XDLCommonSatetMethods(models.AbstractModel):
    # 这里集成了一些对状态state字段的一些通用的操作方法，
    # 比如状态前进或者后退一步，或者完全取消，或者退回初始状态
    _name = 'common.state.methods'

    def _get_current_state_sequence(self):
        # 获取单据中的状态序列
        state_fields = self._fields.get('state')
        class_name = self.__class__.__name__
        if state_fields:
            states = list(zip(*state_fields.selection))[0]
            if not states:
                raise UserError('表单“%s”中的“state”字段可能不是Selection字段！'%class_name)
            elif len(states) <= 1:
                raise UserError('表单"%s"中的state字段状态少于2个！'%class_name)
            else:
                return states
        else:
            raise UserError('表单“%s”中没有找到“state”字段！' %class_name)


    @api.multi
    def common_cancel(self):
        # 默认在倒数第二种状态是“完成”状态，最后一种是“取消”，
        # 默认只能在一级状态下才能取消
        self.ensure_one()
        states = self._get_current_state_sequence()

        if self.state in states[1:]:
            raise UserError('非初始状态下的单据不能取消')
        self.state = states[-1]

    @api.multi
    def common_state_back(self):
        # 状态回退到上一级，否决，取消状态或者初始状态下无效
        self.ensure_one()
        states = self._get_current_state_sequence()
        if self.state == states[-1] or self.state == states[0]:
            return
        pre_state_index = states.index(self.state) - 1
        self.state = states[pre_state_index]
        return

    @api.multi
    def common_state_init(self):
        # 状态初始化，即状态返回到第一级，如果当前处于第一级、
        # 最后一级、倒数第二级，无效
        self.ensure_one()
        states = self._get_current_state_sequence()
        if self.state in (states[0], states[-1], states[-2]):
            return
        else:
            self.state = states[0]


    @api.multi
    def common_state_forward(self):
        # 状态前进到下一级，在取消状态 和 末级状态时无效
        self.ensure_one()
        states = self._get_current_state_sequence()
        if self.state in states[-2:]:
            return
        next_state_index = states.index(self.state) + 1
        self.state = states[next_state_index]
        return



